<template>
  <Form
    v-show="getShow"
    :rules="rules"
    :schema="schema"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)"
    hide-required-asterisk
    label-position="top"
    size="large"
    @register="register"
  >
    <template #title>
      <LoginFormTitle style="width: 100%" />
    </template>

    <template #code="form">
      <div class="w-[100%] flex">
        <el-input v-model="form['code']" placeholder="请输入验证码" />
      </div>
    </template>

    <template #register>
      <div class="w-[100%]">
        <XButton
          :loading="loading"
          title="注册"
          class="w-[100%]"
          type="primary"
          @click="loginRegister()"
        />
      </div>
      <div class="mt-15px w-[100%]">
        <XButton title="已有账号？去登录" class="w-[100%]" @click="handleBackLogin()" />
      </div>
    </template>
  </Form>
</template>
<script lang="ts" setup>
import type { FormRules } from 'element-plus'

import { useFormHooks } from '@/hooks/web/form'
import { useValidatorHooks } from '@/hooks/web/validator'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useLoginState } from './useLogin'
import type { FormSchema } from '@/types/form'

defineOptions({ name: 'RegisterForm' })

const { required } = useValidatorHooks()
const { register, elFormRef } = useFormHooks()
const { handleBackLogin, getLoginState } = useLoginState()
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.REGISTER)

const schema = reactive<FormSchema[]>([
  {
    field: 'title',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'username',
    label: '用户名',
    value: '',
    component: 'Input',
    colProps: {
      span: 24,
    },
    componentProps: {
      placeholder: '请输入用户名',
    },
  },
  {
    field: 'password',
    label: '密码',
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24,
    },
    componentProps: {
      style: {
        width: '100%',
      },
      strength: true,
      placeholder: '请输入密码',
    },
  },
  {
    field: 'check_password',
    label: '确认密码',
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24,
    },
    componentProps: {
      style: {
        width: '100%',
      },
      strength: true,
      placeholder: '请输入密码',
    },
  },
  {
    field: 'code',
    label: '验证码',
    colProps: {
      span: 24,
    },
  },
  {
    field: 'register',
    colProps: {
      span: 24,
    },
  },
])

const rules: FormRules = {
  username: [required()],
  password: [required()],
  check_password: [required()],
  code: [required()],
}

const loading = ref(false)

const loginRegister = async () => {
  const formRef = unref(elFormRef)
  formRef?.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
      } finally {
        loading.value = false
      }
    }
  })
}
</script>
